<template>
    <div class="transform-origin-box" @mousemove="mouseMove" ref="box">
        <div
            class="transform-origin-pointer"
            @mousedown="mouseDown"
            ref="pointer"
            :style="{
                left: `${x}px`,
                top: `${100 - y}px`
            }"
            ></div>
    </div>
</template>

<script>
export default {
    props: {
        x: {
            type: Number,
            default: 50,
        },
        y: {
            type: Number,
            default: 50,
        }
    },
    data() {
        return {
            mousedown: false,
        };
    },
    mounted() {
        document.addEventListener('mouseup', this.mouseUp);
    },
    beforeDestroy() {
        document.removeEventListener('mouseup', this.mouseUp);
    },
    methods: {
        mouseDown(e) {
            e.stopPropagation();
            this.mousedown = true;
        },
        mouseMove(e) {
            if (this.mousedown) {
                e.stopPropagation();
                const { clientX, clientY } = e;
                const box = this.$refs.box.getBoundingClientRect();
                const { left, top } = box;
                let targetLeft = clientX - left;
                let targetTop = clientY - top;
                if (targetLeft < 0) {
                    targetLeft = 0;
                }
                if (targetLeft > box.width) {
                    targetLeft = box.width;
                }
                if (targetTop < 0) {
                    targetTop = 0;
                }
                if (targetTop > box.height) {
                    targetTop = 0;
                }
                this.$refs.pointer.style.left = `${targetLeft}px`;
                this.$refs.pointer.style.top = `${targetTop}px`;
            }
            
        },
        mouseUp() {
            if (this.mousedown) {
                const box = this.$refs.box.getBoundingClientRect();
                const { left, top } = box;
                const pointer = this.$refs.pointer.getBoundingClientRect();
                const { left: pointerLeft, top: pointerTop } = pointer;
                console.log('origin===>', { left: pointerLeft - left, top: 100 - pointerTop + top });
                this.$emit('change', { left: pointerLeft - left, top: 100 - pointerTop + top });
            }
            this.mousedown =  false;
        }
    }
}
</script>

<style lang="less" scoped>
.transform-origin-box {
    position: relative;
    display: inline-block;
    height: 100px;
    width: 100px;
    border: solid 1px #333;
    background-image: url('../assets/image/imageBack.jpeg');
    .transform-origin-pointer {
        position: absolute;
        width: 10px;
        height: 10px;
        display: inline-block;
        border-radius: 100%;
        display: inline-block;
        background: #FFF;
        border: solid 3px #333;
        transform: translate(-50%, -50%);
    }
}
</style>